﻿using LIU.Framework.Common.Extend;
using LIU.Framework.Core.Inject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LIU.Framework.Core.Log
{
    /// <summary>
    /// 日志工厂类
    /// </summary>
    public class LogFactory
    {
        /// <summary>
        /// 缓存日志
        /// </summary>
        private static Dictionary<string, ILogger> LogDics = new Dictionary<string, ILogger>();

        /// <summary>
        /// 构建日志
        /// </summary>
        /// <param name="LogName"></param>
        /// <returns></returns>
        public static ILogger CreateLogger(string LogName)
        {
            if (LogName.IsNullOrWhiteSpace())
            {
                return AppInstance.Current.Resolve<ILogger>();
            }
            else
            {
                if (LogDics.ContainsKey(LogName))
                {
                    return LogDics[LogName];
                }

                ILogger logger = null;
                var logtype = AppInstance.Current.Finder.FindTypes(p => p.GetInterfaces().Contains(typeof(ILogger)) && p != typeof(ILogger) && p.IsClass && !p.IsAbstract).ToArray();
                if (logtype.Any())
                {
                    //有其他的实现就不使用注册默认实现
                    var type = logtype.Where(p => !p.GetInterfaces().Contains(typeof(IDefaultImplementation))).ToArray();
                    if (type.Any())
                        logger = Activator.CreateInstance(type.First(), LogName) as ILogger;
                    else
                        logger = Activator.CreateInstance(logtype.First(), LogName) as ILogger;
                }
                if (logger == null)
                    throw new Exception("日志工厂生成失败：未能查到对应的日志实现类");
                LogDics.Add(LogName, logger);
                return logger;
            }
        }
    }
}
